package com.github.baichuan.application.scaffold.rest.jpa.identity;

import com.github.baichuan.application.scaffold.rest.domain.organization.Org;
import com.github.baichuan.application.scaffold.rest.domain.application.Application;
import com.github.baichuan.application.scaffold.rest.domain.identity.ApplicationMember;
import com.github.baichuan.application.scaffold.rest.domain.identity.Member;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;


import java.util.List;
import java.util.Optional;

public interface ApplicationMemberRepository extends JpaRepository<ApplicationMember, String>, JpaSpecificationExecutor<ApplicationMember> {

    @Query("select am from ApplicationMember am where am.application=:application and am.member=:member")
    Optional<ApplicationMember> find(@Param("application") Application application, @Param("member") Member member);

    List<ApplicationMember> findByMember(Member member);

    @Query("select am from ApplicationMember am where application.code=:application and id=:id")
    Optional<ApplicationMember> find(@Param("application") String application, @Param("id") String applicationMemberId);

    @Query("select am from ApplicationMember am where application.code=:application and am.member.dingUnionId=:unionId")
    Optional<ApplicationMember> findByDingUser(@Param("application") String application, @Param("unionId") String unionId);

    @Query("select am from ApplicationMember am where am.application=:application " +
            "and (am.member.loginName like concat('%', :keyword ,'%') or am.member.name like concat('%', :keyword ,'%'))")
    List<ApplicationMember> suggest(@Param("application") Application application, @Param("keyword") String keyword);

    boolean existsByOrg(Org org);

    @Query(value = "SELECT DISTINCT(resource.code) FROM application_member member \n" +
            "    JOIN application_member_privilege mp ON member.id=mp.application_member_id\n" +
            "    JOIN role ON role.id=mp.role_id\n" +
            "    JOIN role_privilege rp ON rp.role_id=role.id\n" +
            "    JOIN resource ON rp.resource_id=resource.id\n" +
            "WHERE member.id=:memberId AND resource.code is not null",
            nativeQuery = true)
    List<String> getAuthorizationCodes(@Param("memberId") String applicationMemberId);
}
